using System.IO;
using System.Text;
using System;

namespace MvcDependency
{
    public class RenderDependenciesStream : MemoryStream, IDisposable
    {
        private readonly Stream _stream;
        private readonly DependencyManager _manager;
        private readonly Encoding _encoding;
        private readonly MemoryStream _memoryStream = new MemoryStream();

        public RenderDependenciesStream(Stream stream, DependencyManager manager, Encoding encoding)
        {
            _stream = stream;
            _manager = manager;
            _encoding = encoding;
        }

        public override void Flush()
        {
            var content = _encoding.GetString(_memoryStream.ToArray());
            var hadMatch = false;
            if(DependencyManager.JsMarkupRegex.IsMatch(content))
            {
                hadMatch = true;
                content = _manager.ReplaceJsPlaceHolder(content);
            }
            if(DependencyManager.CssMarkupRegex.IsMatch(content))
            {
                hadMatch = true;
                content = _manager.ReplaceCssPlaceHolder(content);
            }

            if(hadMatch)
            {
                var buff = _encoding.GetBytes(content);
                _stream.Write(buff, 0, buff.Length);
            }
            else
            {
                _memoryStream.WriteTo(_stream);
            }
            _stream.Flush();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            _memoryStream.Write(buffer, offset, count);
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if(_memoryStream != null)
                _memoryStream.Dispose();
        }
    }
}